<?php


namespace App\Http\Controllers\Users;



use App\Models\Attendance;
use App\Models\OfficeArea;
use App\Models\User;
use App\Models\UserArea;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class WxappController extends BaseController
{

    /**
     * 登录
     * @param Request $request
     */
    public function login(Request $request){

        //登录
        $input = $request->only('code','raw_data','encrypted_data','iv','signature');

        $result = Validator::make($input, [
            'code' => 'required',
            'raw_data' => 'required',
            'encrypted_data' => 'required',
            'iv'=>'required',
            'signature'=>'required'
        ], [
            'code.required' => '缺少参数！',
            'raw_data.required' => '缺少参数！',
            'encrypted_data.required' => '缺少参数！',
            'iv.required' => '缺少参数！',
            'signature.required' => '缺少参数！',
        ]);

        $token = $request->get('token');

        if ($result->fails()) {
            return $this->json(false,$result->errors()->first());
        }

        //raw_data
        $raw_data = json_decode($input['raw_data'],true);//用户头像昵称信息

        $chofig = config('wechat.mini_program.default');

        $app = Factory::miniProgram($chofig);

        $get_openid = $app->auth->session($input['code']);

        if(!isset($get_openid['openid'])){
            return $this->json(10002,$get_openid['errmsg']);
        }

        //用户是否存在
        $get_user = User::findUser($get_openid['openid']);

        //添加用户
        if(!$get_user){
            $token = md5(uniqid('jhzh', true) . random_int(1, 9999));

            $insert = [
                'name'=>$raw_data['nickName'],
                'avatarurl'=>$raw_data['avatarUrl'],
                'openid'=>$get_openid['openid'],
                'token'=>$token
            ];

            $add = User::adduser($insert);
        }

        //TODO token具体实现
        if(!$token){
            $token = $get_user['token'];
        }

        $data = [
            'openid'=>$get_openid['openid'],
            'session_key'=>$get_openid['session_key'],
            'token'=>$token,
            'get_openid'=>$get_openid,
        ];

        if($get_openid){
            return  $this->json(200,'OK',$data);
        }

        return $this->json(10002,'操作失败!!!!!',$data);
    }

    //获取打卡信息
    public function getPunchTheClock(Request $request){

        $uid = $request->get('auth_uid');
        $to_time = '09:00';
        $off_time = '18:00';
        $date = date('Y-m-d');
        //获取用户信息及是否存在考勤区域信息
        $userareawhere = [
            'id'=>$uid
        ];
        $get_user = User::where($userareawhere)
            ->first();

        if(!$get_user){
            return $this->json(2,'用户信息错误！',$get_user);
        }

        if($get_user['area_id'] <= 0 && $get_user['type'] == 1){

            return $this->json(2,'未设置打卡区域',$get_user);
        }

        //时间
        if($request->get('date')){
            $date = $request->get('date');
        }

        //考勤区域信息
        $area_id = $get_user['area_id'];

        $get_area = OfficeArea::where([
            ['id',$area_id]
        ])
            ->first();

        if(!$get_area && $get_user['type'] == 1){
            return $this->json(2,'考勤区域有误',$get_area);
        }

        //获取考勤记录
        $punch = Attendance::where([
            ['uid',$uid],
            ['date','>',$date],
            ['date','<',date('Y-m-d',strtotime('+1 day',strtotime($date)))]
        ])
            ->orderBy('date','ASC')
//            ->limit(3)
            ->get()
            ->toArray();

        $att = [];
        if($punch){
            foreach ($punch as $k=>$v){
                $card_type = $punch[$k]['card_type']==1?'上班':'下班';
                $mode = $punch[$k]['mode']==1?'办公室':'远程';
                $att[] = [
                    'status_label'=>$punch[$k]['card_type']==1?'上班':'下班',
                    'address'=>$punch[$k]['address'],
                    'punch_time'=>date('H:i',strtotime($punch[$k]['date'])),
                    'worksign_time'=>$punch[$k]['card_type']==1?$to_time:$off_time,
                    'is_external'=>$punch[$k]['mode']==1?'办公室':'远程',
                    'time_label'=>$mode.$card_type,
                ];
            }
        }

        //根据时间得到属于上班还是下班
        $punch_type = 1;//默认上班
//        $h = date('H');
//
//        if($h > 12){
//            $punch_type = 2;
//        }

        //是否存在今天上午打卡信息
        $get_att1 = Attendance::where([
            ['uid',$uid],
            ['date','>',date('Y-m-d')],
            ['card_type',1]
        ])
            ->first();
        if($get_att1){
            $punch_type = 2;
        }

        //用户是否外勤打卡
        $is_external = 2;
        if($get_user['type'] == 2){
            $is_external = 1;
            $get_area = [
                'name'=>'外勤打卡',
                'address'=>'--',
                'latitude'=>'',
                'longitude'=>''
            ];
        }


        $get_user['post_name'] = $get_user['name'];

        $data = [
            'user'=>$get_user,
            'department'=>[
                'name'=>$get_area['name'],
                'post_address'=>$get_area['address']
            ],
            'latitude'=>$get_area['latitude'],
            'longitude'=>$get_area['longitude'],
            'he'=>1,
            'punch_type'=>$punch_type,
            'punch'=>$att,
            'date'=>$date,
            'time'=>date('Y-m-d 18:00'),
            'is_external'=>$is_external,
            'area'=>$get_area,
            'hour'=>''//查询日期上班工时
        ];

        return $this->json(1,'OK',$data);
    }


    //打卡
    public function postPunchTheClock(Request $request){

        $uid = $request->get('auth_uid');

        $input = $request->only(
//            'address',
//            'time_types',
            'x_axis',
            'y_axis',
//            'wifiname',
//            'wifimac',
            'is_external'
        );

        $result = Validator::make($input, [
//            'address' => 'required',
//            'time_types' => 'required',
            'x_axis' => 'required',
            'y_axis'=>'required',
//            'wifiname'=>'required',
//            'wifimac'=>'required',
            'is_external'=>'required'
        ], [
//            'address.required' => '缺少参数！',
//            'time_types.required' => '缺少参数！',
            'x_axis.required' => '缺少参数！',
            'y_axis.required' => '缺少参数！',
//            'wifiname.required' => '缺少参数！',
//            'wifimac.required' => '缺少参数！',
            'is_external.required' => '缺少参数！',
        ]);

        if ($result->fails()) {
            return $this->json(false,$result->errors()->first());
        }

        $input['time_types'] = '';
        $input['wifiname'] = '';
        $input['wifimac'] = '';
        $input['address'] = '';
        $input['img'] = '';
        $input['memo'] = '';//外勤备注 (未添加数据库)

        //固定打卡
        if($input['is_external'] == 2){
            $wifimac = $request->get('wifimac');
            if(!$wifimac){
                return $this->json(2,'wifi信息获取失败',$wifimac);
            }
            $input['time_types'] = $request->get('time_types');
            $input['wifiname'] = $request->get('wifiname');
            $input['wifimac'] = $wifimac;
            $input['address'] = $wifimac;
        }else{
            $input['address'] = $request->get('address');
            $input['img'] = $request->get('img');
        }

        //外勤打卡是否有上传图片
        if($input['is_external'] == 1){
            if(!$input['img']){
                return $this->json(2,'请先拍照！',$input);
            }
        }

        //获取用户信息
        $get_user = User::uidgetUser($uid);

        if(!$get_user){
            return $this->json(2,'用户信息有误',$get_user);
        }

        //是否已打卡
        $get_att = Attendance::where([
            ['uid',$uid],
            ['date','>',date('Y-m-d')],
            ['card_type',$input['time_types']]
        ])
            ->first();

        if($get_att){
            return  $this->json(2,'已打卡！',$get_att);
        }

        //外勤打卡 根据是否打上班卡判断上下班
        if($input['is_external'] == 1){
            $where_1 = [
                ['uid',$uid],
                ['date','>',date('Y-m-d')],
                ['card_type',1]
            ];
            $get_att_1 = Attendance::where($where_1)
                ->first();

            if($get_att_1){
                $input['time_types'] = 2;
            }else{
                $input['time_types'] = 1;
            }
        }

        //添加打卡信息
        $insert = [
            'uid'=>$uid,
            'mac'=>$input['wifimac'],
            'address'=>$input['wifiname'],
            'img'=>$request->get('img')?$request->get('img'):'',
            'date'=>date('Y-m-d H:i:s'),
            'mode'=>$get_user['type'],
            'card_type'=>$input['time_types'],
            'latitude'=>$input['y_axis'],
            'longitude'=>$input['x_axis'],
            'created_at'=>date('Y-m-d H:i:s'),
            'img'=>$input['img'],
        ];

        $in = Attendance::add($insert);

        if(!$in){
            return  $this->json(2,'打卡失败！',$in);
        }

        $data = [];

        return $this->json(1,'OK',$data);
    }

    //待开发
    public function development(Request $request){

        $data = [];

        return $this->json(0,'开发中...',$data);
    }

}
